package com.py.ssh;

import java.util.Properties;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SSHTunnelConnectTest {
	private String strSshUser = "sf"; // SSH loging username
	private String strSshPassword = "test"; // SSH login password
	private String strSshHost = "ip"; // hostname or ip or SSH server
	private int nRemotePort = 3306; // remote port number of your database
	private int nSshPort = 22; // remote SSH host port number
	
	private int nLocalPort = 3366; // local port number use to bind SSH tunnel
	
	public void connect() {
		try {
			// hostname or ip of your database server
			String strRemoteHost = "test.mysql.rds.aliyuncs.com";

			this.doSshTunnel(strSshUser, strSshPassword, strSshHost,
					nSshPort, strRemoteHost, nLocalPort, nRemotePort);
			System.out.println("you can start your businese");
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	
	private Session doSshTunnel(String strSshUser, String strSshPassword,
			String strSshHost, int nSshPort, String strRemoteHost,
			int nLocalPort, int nRemotePort) throws JSchException {
		final JSch jsch = new JSch();
		Session session = jsch.getSession(strSshUser, strSshHost, 22);
		session.setPassword(strSshPassword);

		final Properties config = new Properties();
		config.put("StrictHostKeyChecking", "no");
		session.setConfig(config);

		session.connect();
		System.out.println("Connected");
		int assinged_port = session.setPortForwardingL(nLocalPort,
				strRemoteHost, nRemotePort);
		System.out.println("localhost:" + assinged_port + " -> "
				+ strRemoteHost + ":" + nRemotePort);
		System.out.println("Port Forwarded");
		
		return session;
	}
	
	
	public static void main(String[] args) {
		SSHTunnelConnectTest conn = new SSHTunnelConnectTest();
		conn.connect();
	}
}
